package org.oneblog.data.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

public class BaiduSitePostUtil {
    public static String post(String PostUrl, String[] Parameters) {
        if (null == PostUrl || null == Parameters || Parameters.length == 0) {
            return null;
        }
        String result = "";
        PrintWriter out = null;
        BufferedReader in = null;
        try {
            // 建立URL之间的连接
            URLConnection conn = new URL(PostUrl).openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("Host", "data.zz.baidu.com");
            conn.setRequestProperty("User-Agent", "curl/7.12.1");
            conn.setRequestProperty("Content-Length", "83");
            conn.setRequestProperty("Content-Type", "text/plain");

            // 发送POST请求必须设置如下两行
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // 获取conn对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            String param = "";
            for (String s : Parameters) {
                param += s + "\n";
            }
            out.print(param.trim());
            // 进行输出流的缓冲
            out.flush();
            // 通过BufferedReader输入流来读取Url的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

        } catch (Exception e) {
            System.out.println("发送post请求出现异常！" + e);
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }

            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        // String basePath = "F:/workspace/";
        //
        // System.out.println(sum(new File(basePath)));

        List<String> urls = new ArrayList<String>();
        urls.add("https://www.oomabc.com/articledetail?atclid=21804c3431194c0c8c6937c481d94870");
        urls.add("https://www.oomabc.com/articledetail?atclid=1c46fb8390d94717aa5106957272e02c");
        urls.add("https://www.oomabc.com/articledetail?atclid=c028115c114c4c42ac5a8c20e59f1020");
        urls.add("https://www.oomabc.com/articledetail?atclid=86efdbab652d44a1a00e03f07c353be8");
        urls.add("https://www.oomabc.com/list");

        System.out.println(post("http://data.zz.baidu.com/urls?site=https://www.oomabc.com&token=kuhkoaCn8ehIYbvQ", urls.toArray(new String[urls.size()])));
    }
}
